<?php
namespace app\common\logic;

use think\facade\Db;
use think\Session;

class AdminLogic
{
    public function login($username, $password)
    {
        if (empty($username) || empty($password)) {
            return ['status' => 0, 'msg' => '请填写账号密码'];
        }

        $condition['a.user_name'] = $username;
        $condition['a.password'] = encrypt($password);
        $admin = Db::name('admin')->alias('a')->join('admin_role ar', 'a.role_id=ar.role_id')->where($condition)->find();
        if (!$admin) {
            return ['status' => 0, 'msg' => '账号密码不正确'];
        }
        if($admin['suppliers_id']>0){
            $supply = Db::name('suppliers')->where('id',$admin['suppliers_id'])->find();
            if($supply['status']==0){
                return ['status' => 0, 'msg' => '账号等待审核中'];
            }
            if($supply['status']==2){
                return ['status' => 0, 'msg' => '账号审核未通过'];
            }
        }
        $this->handleLogin($admin, $admin['act_list']);

        $url = session('from_url') ? session('from_url') : url('Index/index');
        if($admin['suppliers_id']>0){
            $url = url('Index/index');
        }
        return ['status' => 1, 'url' => $url];
    }

    public function handleLogin($admin, $actList)
    {
        Db::name('admin')->where('admin_id', $admin['admin_id'])->save([
            'last_login' => time(),
            'last_ip' => request()->ip()
        ]);

        session('act_list', $actList);
        session('admin_name', $admin['user_name']);
        session('admin_id', $admin['admin_id']);
        session('expire_time',time()+86400);
        session('suppliers_id', $admin['suppliers_id']);
        if(!defined('SID')){
            define('SID', $admin['suppliers_id']);
        }
    }
}






